package com.xywh.wanandroid.compose_ui.main

import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DrawerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xywh.composeLibrary.view.XxImage
import com.xywh.composeLibrary.view.XxImageVector
import com.xywh.wanandroid.R
import com.xywh.wanandroid.event.EventViewModel.Companion.getUserInfoBean
import com.xywh.wanandroid.event.EventViewModel.Companion.isLogin
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.util.CacheUtil
import com.xywh.wanandroid.viewmodel.MainComposeViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Composable
fun MainDrawerContent(
    mainComposeViewModel: MainComposeViewModel,
    navigateRank: () -> Unit,
    navigateLogin: () -> Unit,
    navigateScore: () -> Unit,
    navigateCollect: () -> Unit
) {
    ModalDrawerSheet(
        modifier = Modifier.padding(end = 90.dp),
        drawerContainerColor = Color.White
    ) {
        val items =
            listOf(
                "我的积分",
                "我的收藏",
//                "我的分享",
//                "TODO",
//                "夜间模式",
//                "系统设置",
                "退出登录"
            )
        val itemsIcon = listOf(
            R.drawable.ic_home_black_24dp,
            R.drawable.ic_like_not,
//            R.drawable.ic_share_white_24dp,
//            R.drawable.ic_todo_default_24dp,
//            R.drawable.ic_night_24dp,
//            R.drawable.ic_setting_24dp,
            R.drawable.ic_logout_white_24dp
        )

        Column(Modifier.background(MaterialTheme.colorScheme.primary)) {


            Row(
                horizontalArrangement = Arrangement.End,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(end = 10.dp)

            ) {
                XxImageVector(
                    R.drawable.ic_rank_white_24dp,
                    size = 20.dp,
                    top = 20.dp
                ) {
                    navigateRank.invoke()
                }
            }
            Column(
                Modifier
                    .background(Color.Transparent)
                    .fillMaxWidth()
                    .height(135.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {

                XxImage(
                    R.drawable.ic_default_avatar,
                    size = 70.dp,
                    roundedCornerShape = 50,
                    borderWidth = 2.dp,
                    borderColor = Color.White,
                    borderShape = CircleShape
                )


                var username = "去登录"
                var gradeRank = "等级:-- 排名:--"

                if (isLogin.value) {
                    val user = CacheUtil.getUser()
                    user?.let {
                        username = it.username
                    }
                }
                if (getUserInfoBean.value) {
                    val userInfoBean = CacheUtil.getUserInfoBean()
                    userInfoBean?.let {
                        gradeRank =
                            "等级:${it.coinCount / 100 + 1} 排名:${it.rank} "
                    }
                }


                Text(
                    modifier = Modifier
                        .padding(top = 10.dp)
                        .clickable {
                            if (!isLogin.value) {
                                navigateLogin.invoke()
                            }
                        },
                    text = username,
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    modifier = Modifier.padding(top = 5.dp),
                    text = gradeRank,
                    color = Color.White,
                    fontSize = 10.sp,
                )
            }
            Column(Modifier.background(Color.White)) {
                val selectedItem = remember { mutableStateOf(items[0]) }

                items.forEachIndexed { index, item ->

                    if (index == 2) {
                        val openDialog = remember { mutableStateOf(false) }
                        if (openDialog.value)
                            LayoutDialog(mainComposeViewModel, openDialog)
                        if (isLogin.value) {
                            NavigationDrawerItem(
                                icon = {
                                    XxImageVector(
                                        imageVectorId = itemsIcon[index],
                                        contentDescription = item,
                                        size = 20.dp,
                                        colorFilter = ColorFilter.tint(Color.Black)
                                    )
                                },
                                label = { Text(item, fontSize = 14.sp) },
                                selected = item == selectedItem.value,
                                onClick = {
//                                    navigationDrawerItemOnClick.invoke(index)
//                                    scope.launch { drawerState.close() }
                                    selectedItem.value = item
                                    openDialog.value = true


                                },
                                modifier = Modifier
                                    .padding(NavigationDrawerItemDefaults.ItemPadding),
                                colors = NavigationDrawerItemDefaults.colors(
                                    selectedContainerColor = Color.White,
                                    unselectedContainerColor = Color.White
                                )
                            )
                        }

                    } else {
                        NavigationDrawerItem(
                            icon = {
                                XxImageVector(
                                    imageVectorId = itemsIcon[index],
                                    contentDescription = item,
                                    size = 20.dp,
                                    colorFilter = ColorFilter.tint(Color.Black)
                                )
                            },
                            label = { Text(item, fontSize = 14.sp) },
                            selected = item == selectedItem.value,
                            onClick = {
//                                navigationDrawerItemOnClick.invoke(index)
//                                scope.launch { drawerState.close() }
                                selectedItem.value = item

                                when (index) {
                                    0 -> {
                                        if (isLogin(navigateLogin))
                                            navigateScore.invoke()
                                    }

                                    1 -> {
                                        if (isLogin(navigateLogin))
                                            navigateCollect.invoke()

                                    }

//                                    2 -> {
//                                        darkTheme.value = !darkTheme.value
//                                        CacheUtil.setDarkTheme(darkTheme.value)
//                                    }

                                }

                            },
                            modifier = Modifier
                                .padding(NavigationDrawerItemDefaults.ItemPadding),
                            colors = NavigationDrawerItemDefaults.colors(
                                selectedContainerColor = Color.White,
                                unselectedContainerColor = Color.White
                            )
                        )
                    }

                }

            }
        }


    }
}

private fun isLogin(navigateLogin: () -> Unit): Boolean {
    return if (!isLogin.value) {
        showToastMsg("请先登录")
        navigateLogin.invoke()
        false
    } else {
        true
    }
}

@Composable
fun LayoutDialog(mainComposeViewModel: MainComposeViewModel, openDialog: MutableState<Boolean>) {


    AlertDialog(
        onDismissRequest = {
            // Dismiss the dialog when the user clicks outside the dialog or on the back
            // button. If you want to disable that functionality, simply use an empty
            // onDismissRequest.
            openDialog.value = false
        },
        title = {
            Text(text = "提醒", fontSize = 16.sp, fontWeight = FontWeight.Bold)
        },
        text = {
            Text(text = "确认退出登录？", fontSize = 14.sp)
        },
        confirmButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                    mainComposeViewModel.logout() {
                        mainComposeViewModel.updateCollectArticleListData()
                    }
                }
            ) {
                Text("确定", fontSize = 14.sp)
            }
        },
        dismissButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                }
            ) {
                Text("取消", fontSize = 14.sp)
            }
        },
        containerColor = Color.White,
        shape = RoundedCornerShape(10)
    )
}

@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
fun MainTopBar(
    pagerState: PagerState,
    scope: CoroutineScope,
    drawerState: DrawerState,
    scrollBehavior: TopAppBarScrollBehavior,
    modifier: Modifier = Modifier,
    actionsIconOnClick: () -> Unit
) {
    val menusName = arrayListOf("首页", "广场", "公众号", "体系", "项目")

//    val density = LocalDensity.current
//    AnimatedVisibility(
//        visibleState = transitionState,
//
//        enter = slideInVertically(tween(100)) {
//            // Slide in from 40 dp from the top.
//            with(density) { -40.dp.roundToPx() }
//        } + expandVertically(
//            // Expand from the top.
//            tween(100),
//            expandFrom = Alignment.Bottom
//        ) + fadeIn(
//            tween(100),
//            // Fade in with the initial alpha of 0.3f.
//            initialAlpha = 0.3f
//        ),
//        exit = slideOutVertically(tween(100)) + shrinkVertically(tween(100)) + fadeOut(tween(100))
//    ) {
    TopAppBar(
        title = { Text(menusName[pagerState.currentPage], color = Color.White) },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primary
        ),
        navigationIcon = {
            IconButton(
                onClick = { scope.launch { drawerState.open() } }
            ) {
                Icon(
                    Icons.Filled.Menu,
                    contentDescription = "Localized description",
                    tint = Color.White
                )
            }
        },
        modifier = modifier.statusBarsPadding(),

        actions = {
            IconButton(onClick = {
                actionsIconOnClick.invoke()
            }) {
                Icon(
                    Icons.Filled.Search,
                    contentDescription = "Menu",
                    tint = Color.White
                )
            }
        },
        scrollBehavior = scrollBehavior

    )
//    }

}


@OptIn(ExperimentalAnimationApi::class)
@Composable
fun MainFloatingActionButton(
    onClick: () -> Unit

) {
//    AnimatedVisibility(
//        visibleState = transitionState,
//        enter = scaleIn(tween(100)) + expandVertically(
//            tween(100),
//            expandFrom = Alignment.CenterVertically
//        ),
//        // Shrinks the content to half of its full height via an animation.
//        exit = scaleOut(tween(100)) + shrinkVertically(
//            tween(100),
//            shrinkTowards = Alignment.CenterVertically
//        ),
//    ) {
    //FilledIconButton 圆形按钮
    FloatingActionButton(
        containerColor = MaterialTheme.colorScheme.primary,
        onClick = {
            onClick.invoke()
        }
    ) {

        XxImageVector(
            imageVectorId = R.drawable.ic_arrow_upward_white_24dp,
            contentDescription = "",
            size = 30.dp
        )
    }
//    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MainBottomBar(
    pagerState: PagerState,
    scope: CoroutineScope,
) {
//    val density = LocalDensity.current
//    AnimatedVisibility(
//        visibleState = transitionState,
//
//        enter = slideInVertically(tween(100)) {
//            // Slide in from 40 dp from the top.
//            with(density) { -40.dp.roundToPx() }
//        } + expandVertically(
//            tween(100),
//            // Expand from the top.
//            expandFrom = Alignment.Top
//        ) + fadeIn(
//            tween(100),
//            // Fade in with the initial alpha of 0.3f.
//            initialAlpha = 0.3f
//        ),
//        exit = slideOutVertically(tween(100)) + shrinkVertically(tween(100)) + fadeOut(tween(100))
//    ) {
    val items = listOf("首页", "广场", "公众号", "体系", "项目")
    val itemsIcon = listOf(
        R.drawable.ic_home_black_24dp,
        R.drawable.ic_square_black_24dp,
        R.drawable.ic_wechat_black_24dp,
        R.drawable.ic_apps_black_24dp,
        R.drawable.ic_project_black_24dp,
    )
    NavigationBar(
        containerColor = Color.White
    ) {
        items.forEachIndexed { index, item ->
            NavigationBarItem(
                icon = {
                    XxImageVector(
                        imageVectorId = itemsIcon[index],
                        contentDescription = item,
                        size = 25.dp,
                    )
                },
                label = { Text(item) },
                selected = pagerState.currentPage == index,
                onClick = {
                    scope.launch {
                        pagerState.animateScrollToPage(index)
                    }
                }
            )
        }
    }
//    }
}